"""--------------------------------------------------------------------------------------------------
Filename:   serialFind.py
Author:     Chris Chester (christopher.chester@pg.canterbury.ac.nz)
Date:       26 July 2012
Description:
   Module for finding serial ports and their names
   Note: Code was adapted from http://www.digi.com/wiki/developer/index.php/Connect_Port_Serial_Port_Access
--------------------------------------------------------------------------------------------------"""

import _winreg as winreg
import itertools
import re

MAX_PORTS = 10


#===============================================================================
# CLASS: SerialFind
#    Contains method for finding the port at which the bioimpedance device is
#    connected
#===============================================================================
class SerialFind():
    
    def __init__(self):
        self.ports = []
        
        
    def enumerate_serial_ports(self):
        '''Creates a list of the active serial ports'''
        
        path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        
        #Obtains a list of all of the serial ports connected
        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        except WindowsError:
            raise
        
        # Iterates through the ports to create a list of ports
        for portNum in range(0, MAX_PORTS):
            try:
                val = winreg.EnumValue(key, portNum)
                self.ports.append(val)                

            except EnvironmentError:
                break
            
        return self.ports
            

    def full_port_name(self,portname):
        """ Given a port-name (of the form COM7, COM12, CNCA0, etc.) returns a full
            name suitable for opening with the Serial class. If no name found, returns
            given name with \\\\.\\ attached to the start as a guess.
        """
        # Finds if there is a match between the port name and the ports available.
        match = re.match('^COM(\d+)$', portname)
        if match and int(match.group(1)) < MAX_PORTS:
            return portname
        
        return '\\\\.\\' + portname


#end of SelialFind